package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.constant.MessageConstant;
import com.example.dto.NovelDTO;
import com.example.dto.PageDTO;
import com.example.entity.Category;
import com.example.entity.Novel;
import com.example.mapper.NovelMapper;
import com.example.query.NovelQuery;
import com.example.result.Result;
import com.example.service.ICategoryService;
import com.example.service.INovelService;
import com.example.vo.NovelVO;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class NovelServiceImpl extends ServiceImpl<NovelMapper, Novel> implements INovelService {

    private final ICategoryService categoryService;
//    private final RedisTemplate redisTemplate;

    /*
     * 添加小说
     * @param novelDTO
     * @return
     * */
    @Override
    public void addNovel(NovelDTO novelDTO) {
        String title = novelDTO.getTitle();
        Novel novel = getNovel(title);
        if (novel != null) {
            throw new RuntimeException(MessageConstant.NOVEL_ALREADY_EXISTS);
        }
        Novel newNovel = Novel.builder()
                .title(title)
                .authorName(novelDTO.getAuthorName())
                .description(novelDTO.getDescription())
                .avatar(novelDTO.getAvatar())
                .category(novelDTO.getCategory())
                .publishTime(novelDTO.getPublishTime())
                .status(1)
                .build();
        save(newNovel);
    }


    /*
     * 小说分页查询
     * @param novelQuery
     * @return
     * */
    @Override
    public Result<PageDTO<NovelVO>> QueryNovelpage(NovelQuery novelQuery) {
        //判断缓存中是否存在
        PageDTO<NovelVO> pageDTO = null;
//        String key = "novels";
//        if (novelQuery.getPublishTime() == null && novelQuery.getTitleOrAuthor() == null && novelQuery.getCategory() == null && novelQuery.getStatus() == 2) {
//            pageDTO = (PageDTO<NovelVO>) redisTemplate.opsForValue().get(key);
//            if (pageDTO != null) {
//                return Result.success(pageDTO);
//            }
//        }
        String titleOrAuthor = novelQuery.getTitleOrAuthor();
        String category = novelQuery.getCategory();
        String publishTime = novelQuery.getPublishTime();
        Integer status = novelQuery.getStatus();
        //构造分页对象
        Page<Novel> page = novelQuery.toMpPage();
        //构造查询条件
        Page<Novel> p = lambdaQuery()
                .apply(titleOrAuthor != null, "(title LIKE {0} OR author_name LIKE {0})", "%" + titleOrAuthor + "%")
                .eq(category != null, Novel::getCategory, category)
                .eq(publishTime != null, Novel::getPublishTime, publishTime)
                .eq(Novel::getStatus, status)
                .page(page);
        //转换为VO
        pageDTO = PageDTO.of(p, NovelVO.class);
//        if (novelQuery.getPublishTime() == null && novelQuery.getTitleOrAuthor() == null && novelQuery.getCategory() == null && novelQuery.getStatus() == 2) {
//            redisTemplate.opsForValue().set(key, pageDTO);
//        }
        return Result.success(pageDTO);
    }

    /*
     * 修改小说
     * @param novelDTO
     * @return
     * */
    @Override
    public void updateNovel(NovelDTO novelDTO) {
        String title = novelDTO.getTitle();
        Novel novel = getNovel(title);
        Novel existingNovel = getById(novelDTO.getId());
        //判断标题是否重复
        if (novel != null && !existingNovel.getId().equals(novel.getId())) {
            throw new RuntimeException(MessageConstant.NOVEL_ALREADY_EXISTS);
        }
        BeanUtils.copyProperties(novelDTO, existingNovel);
        if (novelDTO.getCategory() != null) addCategory(novelDTO);
        updateById(existingNovel);
    }

    /*
     * 根据小说名查询小说
     * @param title
     * @return
     * */
    private Novel getNovel(String title) {
        LambdaQueryWrapper<Novel> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Novel::getTitle, title);
        Novel novel = getOne(queryWrapper);
        return novel;
    }

    /*
     * 添加分类
     * @param novelDTO
     * @return
     * */
    private void addCategory(NovelDTO novelDTO) {
        Category category = Category.builder()
                .name(novelDTO.getCategory())
                .build();
        categoryService.addCategory(category);
    }
}
